package com.jiazhong.schedule.controller;


import com.jiazhong.schedule.pojo.SysUser;
import com.jiazhong.schedule.service.SysUserService;
import com.jiazhong.schedule.service.impl.SysUserServiceImpl;
import com.jiazhong.schedule.utils.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/*")
public class UserController extends BaseController {
    private SysUserService userService = new SysUserServiceImpl();

    /// 注册
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = MD5Util.encrypt(req.getParameter("password"));
        SysUser sysUser = new SysUser(null, username, password);
        int row = userService.addSysUser(sysUser);
        if (row > 0) {
            resp.sendRedirect("/schedule_system_war/login.html");
        } else {
            resp.sendRedirect("/schedule_system_war/err.html");
        }
    }

    /// 登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = MD5Util.encrypt(req.getParameter("password"));
        SysUser sysUser = userService.login(username);
        if (sysUser == null) {
            resp.sendRedirect("/schedule_system_war/err.html");
        } else if (!password.equals(sysUser.getUserPwd())) {
            resp.sendRedirect("/schedule_system_war/err.html");
        } else {
            req.getSession().setAttribute("sysUser", sysUser);
            resp.sendRedirect("/schedule_system_war/showdata.html");
        }

    }
}
